﻿namespace LS.Nc6.Web.Entry.Areas.Systems.Controllers
{
    [Route("[area]/[controller]/[action]")]
    [Area("Systems")]
    [ApiDescriptionSettings("Default")]
    public class OrganizeController : BaseAdminController
    {

        #region OrganizeController
        private readonly ISysRoleService _roleService;
        private readonly ISysOrganizeService _organizeService;
        private readonly ISysUserService _userService;
        private readonly ISysFileService _fileService;
        private readonly ICache _cache;
        public OrganizeController(ISysRoleService roleService, ISysOrganizeService organizeService, ISysUserService userService, ISysFileService fileService, IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            : base(cacheOptions, resolveNamed)
        {
            _roleService = roleService;
            _organizeService = organizeService;
            _userService = userService;
            _fileService = fileService;
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
        }
        #endregion

        #region 页面
        public ActionResult Index()
        {
            SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            ViewBag.AccessUpdate = SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(),false);
            ViewBag.AccessDelete = SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            return View();
        }
        public ActionResult CreateOrg()
        {
            SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            var model = new SysOrganizeEntity();
            string strwhere = string.Empty;
            var parentId = Request.Query["parentId"].ToString().GetQueryValueOrNull<int>(0); 
          
            model.ParentId = parentId;
            model.Isenable = true;
            return View("EditOrg", model);
        }
        public async Task<ActionResult> EditOrg(long id)
        {
            SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            //SysPower(new List<string>() { SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.MENU_ORGSERV_ORGUSER }, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model = await _organizeService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
          
            ViewBag.FileList =await _fileService.CustomerFileList(model.FileIDs);
            return View(model);
        }
        #endregion

        #region 公共方法
        [HttpGet]
        public async Task<dynamic> GetOrganizeDtree()
        {
            return new
            {
                code = 0,
                msg = "操作成功",
                data = await GetOrgDTreeAllData()
            };
        }
        
        [HttpGet]
        public async  Task<ResponseResultDataList> GetAllOrganizeList()
        {
            string orgname = RequestHelper.FilterParam(Request.Query["orgname"]);
            string orgcode = RequestHelper.FilterParam(Request.Query["orgcode"]);
            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];
            var expable = Expressionable.Create<SysOrganizeEntity>();

            //if (UserInfo.UserType != 1)
            //{
            //    var model = ISysUserService.GetById(UserInfo.ID);
            //    strwhere += $" and id='{model.CompanyId}' ";
            //}
            expable.AndIF(!string.IsNullOrEmpty(orgname), a => a.OrgName.Contains(orgname));
            expable.AndIF(!string.IsNullOrEmpty(orgcode), a => a.OrgCode.Contains(orgcode));
            var exp = expable.ToExpression();
            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<SysOrganizeEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = (a) => new { a.Id };
            }
            else
            {
                //实现字段排序
                expressionOrder = (a) => new { a.CreateDate };
            }
            //string filed = " *,(select count(1) From sys_organizeuser where orgcode=sys_organize.orgcode or (orgcode like sys_organize.orgcode+'%' )) as Members ";
            var result = await _organizeService.PageList(exp, page, limit, expressionOrder);

            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Items, count = result.TotalCount };
        }


        [HttpGet]
        public async Task<ResponseResultDataList> GetXmSelectList()
        {
            string orgname = RequestHelper.FilterParam(Request.Query["orgname"]);
            string id = RequestHelper.FilterParam(Request.Query["id"]);
            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];

            //var userinfoModel =await _userService.GetByIdAsync(UserInfo.ID);

            var expable = Expressionable.Create<SysOrganizeEntity>();
            expable.AndIF(!string.IsNullOrEmpty(orgname), a => a.OrgName.Contains(orgname));
            expable.AndIF(!string.IsNullOrEmpty(id), a => a.Id==id.ParseToLong());
            var exp = expable.ToExpression();

            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<SysOrganizeEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = (a) => new { a.Id };
            }
            else
            {
                //实现字段排序
                expressionOrder = (a) => new { a.CreateDate };
            }
            var result =await _organizeService.PageList(exp, page, limit, expressionOrder);
            List<Hashtable> list = new List<Hashtable>();
            foreach (var item in result.Items)
            {
                Hashtable hs = new Hashtable();
                hs.Add("name", item.OrgName);
                hs.Add("value", item.Id);
                hs.Add("contact", item.Contact);
                if (id == item.Id.ToString())
                {
                    hs.Add("selected", true);
                }
                list.Add(hs);
            }
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = list, count = list.Count };
        }
        /// <summary>
        /// 获取分类详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseDataResult> GetModel(long id)
        {
            var model =await _organizeService.GetByIdAsync(id);
            model.FileList = await _fileService.CustomerFileList(model.FileIDs);
            return new ResponseDataResult { code = ResponseHelper.SEUCCESSCODE, message = "获取成功", data = model };
        }
        /// <summary>
        /// 保存组织机构
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveOrgRole([FromBody]SysOrganizeEntity model)
        {
            bool power = true;
            List<SysOrganizeRoleEntity> list = new List<SysOrganizeRoleEntity>();
            //处理角色 功能
            //var listrolecode = RequestHelper.GetStringListNoNull("rolecode");
            //foreach (var item in listrolecode)
            //{
            //    list.Add(new SysOrganizeRoleEntity
            //    {
            //        OrgCode = model.OrgCode,
            //        RoleCode = item
            //    });
            //}
            long result = 0;
            if (model.Id > 0)
            {
                //power = SysPower(new List<string>() { SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.MENU_ORGSERV_ORGUSER }, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
               power = SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel =await _organizeService.GetByIdAsync(model.Id);
                if(editmodel ==null || editmodel.IsDeleted==1)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.OPERATE_SJYSC);
                }
                CommonMethodHelper.MapperToModel(editmodel, model, null);
                //result = ISysOrgService.UpdateOrgRole(editmodel, list);
                result= await _organizeService.UpdateAsync(editmodel);
            }
            else
            {
                //power = SysPower(new List<string>() { SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.MENU_ORGSERV_ORGUSER }, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                power = SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                //result = ISysOrgService.InsertOrgRole(model, list);
                result =await _organizeService.InsertAsync(model);
            }
           return  ResponseHelper.SaveResult(result);
           
        }
      

        /// <summary>
        /// 删除组织结构
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> DelOrg([FromBody]DeletDataInput input)
        {
            //var r = SysPower(new List<string>() { SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.MENU_ORGSERV_ORGUSER }, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            var r = SysPower(SysMenuConstant.MENU_ORGANIZE_MANAGE, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
            }
            if (string.IsNullOrEmpty(input.Ids))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            int result = await _organizeService.DeleteAsync(input.Ids);
            if (result > 0)
            {
               var userlist= await _userService.List((a) => input.Ids.GetStringArrayNoNull().Contains(a.CompanyId.ToString()),null);
               var ids  = userlist.Select(x => x.Id.ToString()).ToArray();
               await _userService.DeleteAsync(string.Join(",", ids));
            }
            return ResponseHelper.DeleteResult(result);
        }

        /// <summary>
        /// 获取dtree  数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<dynamic> GetdtreeData(long id)
        {

            List<Hashtable> lsetm = new List<Hashtable>();
            var menulist = await _organizeService.List(a => a.Isenable == true && a.Id != id, (a) => new { a.Id });
            foreach (var item in menulist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("id", item.Id.ToString());
                etm.Add("title", item.OrgName);
                etm.Add("parentId", item.ParentId.ToString());
                lsetm.Add(etm);
            }

            return new
            {
                code = 0,
                msg = "操作成功",
                data = lsetm
            };

        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 树形数据
        /// </summary>
        /// <returns></returns>
        private async Task<List<Hashtable>> GetOrgDTreeAllData()
        {
            List<Hashtable> lsetm = new List<Hashtable>();
            long companyId =0 ;

            if (UserInfo.UserType!=1)
            {
                var model= await _userService.GetByIdAsync(UserInfo.ID);
                companyId = model!=null? model.CompanyId.Value:0;
            }
            List<SysOrganizeEntity> orglist = null;
            if (companyId>0)
            {
                 orglist = await _organizeService.List(it => it.Id == companyId, it => new { it.Id });
            }
            else
            {
                 orglist = await _organizeService.List(it => true, it => new { it.Id });
            }
            //添加默认
            Hashtable etmdefault = new Hashtable();
            etmdefault.Add("id", 0);
            etmdefault.Add("parentId", -1);
            etmdefault.Add("title", "部门管理");
            etmdefault.Add("checkArr", "0");
            lsetm.Add(etmdefault);
           
            foreach (var item in orglist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("id", item.Id.ToString());
                etm.Add("parentId", item.ParentId);
                etm.Add("title", item.OrgName.ToString());
                etm.Add("checkArr", "0");
                lsetm.Add(etm);
            }
            return lsetm;
        }
        /// <summary>
        /// 树形数据
        /// </summary>
        /// <returns></returns>
        private List<Hashtable> GetOrgDTreeAllDataCustomer(string ids)
        {
            List<Hashtable> lsetm = new List<Hashtable>();
            List<Hashtable> lsetm2 = new List<Hashtable>();
            string strwhere = " and  Isdel=0  order by  Members desc ";
            //if (UserInfo.UserType != 1)
            //{
            //    var model = ISysUserService.GetById(UserInfo.ID);
            //    strwhere += $" and id='{model.CompanyId}' ";
            //}

            var orglist = _organizeService.GetSignContractList(strwhere);

            var  custorg= CommonUtil.GetStringListNoNull(ids);

            //添加默认
            Hashtable etmdefault = new Hashtable();
            etmdefault.Add("id", 0);
            etmdefault.Add("parentId", -1);
            etmdefault.Add("title", "部门管理");
            etmdefault.Add("checkArr", "0");
            lsetm.Add(etmdefault);

            foreach (var item in orglist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("id", item.Id.ToString());
                etm.Add("parentId", item.ParentId);
                if (custorg.Contains(item.Id.ToString()))
                {
                    etm.Add("title", item.OrgName.ToString()+"[签]");
                    etm.Add("checkArr", "0");
                    lsetm2.Add(etm);
                }
                else
                {
                    etm.Add("title", item.OrgName.ToString());
                    etm.Add("checkArr", "0");
                    lsetm.Add(etm);
                }
            }
            return lsetm2.Concat(lsetm).ToList();
        }
       

        #endregion

    }
}